package Year21_Month10.day1026;

import java.util.Arrays;

public class Stack<E>{
    E[] array;
    int size;

    public Stack(){
        array = (E[])new Object[3];//会直接初始化一个初始容量被
        size = 0;
    }

    //压栈的方法
    public void push(E e){
        ensureCapacity();//首先要扩容吧

        array[size] = e;
        size++;
    }
    //扩容方法
    public void ensureCapacity(){
        if(size >= array.length){
            int old = array.length;
            array = Arrays.copyOf(array,old * 2);
        }
    }

    //取出栈顶元素，就是直接删除
    public E pop(){
        E e = array[size - 1];
        size--;
        return e;
    }

    public E peek(){
        if(size == 0){
            throw new NullPointerException("栈是空的");
        }

        return array[size - 1];
    }

    //判断是否为空
    public boolean empty(){
        return size == 0;
    }

    public String toString(){
        String s = "[";
        for(int i = size - 1;i > 0;i--){
            s += array[i] + ",";
        }
        s += array[0] + "]";
        return s;
    }
    //开始测试
    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(0);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack);

        stack.pop();
        System.out.println(stack);

        stack.peek();
        System.out.println(stack);

        System.out.println(stack.size);
        System.out.println(stack.empty());
    }

}
